<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>书签</title>
  <style>
    #top {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 3px 7px;
    }

    #out {
      display: block;
      background: #e56464;
      width: 55px;
      height: 26px;
      line-height: 26px;
      text-align: center;
      border-radius: 22px;
      color: white;
    }

    #tip,
    #fileName {
      display: inline;
    }

    .tip {
      background: #959595;
      color: wheat;
      padding: 5px;
      margin: 0;
      margin-bottom: 2px;
      word-break: break-all;
      min-height: 22px;
    }

    .folder {
      background: #e5e3ca;
      display: flex;
      padding: 12px 8px;
      align-items: center;
      color: black;
      font-size: 18px;
      border-bottom: 1px solid #f3f2f1;
      position: relative;
    }

    .link {
      /* background: #91d8d3; */
      display: flex;
      padding: 12px 8px;
      align-items: center;
      color: black;
      font-size: 18px;
      border-bottom: 1px solid #bebebe;
      position: relative;
    }

    .zz {
      position: absolute;
      width: 100%;
      height: 100%;
      left: 0;
    }

    .img {
      max-width: 26px;
      margin-right: 10px;
      width: 26px;
      height: 26px;
    }

    #refresh {
      /* position: fixed;
      top: 12px;
      right: 20px; */
      width: 40px;
      height: 40px;
      background-color: antiquewhite;
      z-index: 9999;
      border-radius: 12px;
      font-size: 30px;
      cursor: pointer;
    }
  </style>
</head>

<body style="background: #e9e9e9; margin: 0; padding: 0; position: relative;">

  <div id="top">
    <div id="out" onclick="outFn()">退出</div>
    <div id="refresh" onclick="refreshFn()">🚶‍♂️</div>
  </div>

  <div class="tip">
    <div id="fileName"></div>/
    <div id="tip"></div>
  </div>

  <div id="folderDir" onclick="folderFn(event)">
    <!-- <div class="folder">
      <img class="img" src="../images/folder.svg">
      <div>视频1</div>
    </div> -->
  </div>

  <div id="linkDir" style="margin-bottom: 70px;" onclick="openLink(event)">
    <!-- <div class="link">
      <img class="img" src="../images/链接.png">
      <div>视频3</div>
      <div class="zz"></div>
    </div> -->
  </div>
</body>

<script src="../js/local.js"></script>

<script>
  /* 获取书签文件Blob */
  function getFileContent(path) {
    let than = this
    // console.log(`path`, path)
    fetch("/getFileContent?path=" + path, {
      method: 'GET',
    }).then(res => res.json())
      .catch((error) => {
        // console.log('获取文件Blob ', error)
      })
      .then((resp) => {
        try {
          tipArr = [];
          changeTip();
          db.setData('bookmarks', resp)
          history.replaceState({}, '', '#start')
          location.reload()
        } catch (e) {
          alert("请求书签数据出差")
        }
      })
  }


  // 根据书签id重组成对象
  let obj = {}
  function bookmarksToObj(data) {
    obj['start'] || (obj['start'] = bookmarks);
    data.forEach((item, index) => {
      if (item.children) {
        obj[item.id] = item;
        bookmarksToObj(item.children)
      } else obj[item.id] = item;
    })
  }

  /* 渲染书签到页面 */
  function addBookmarks(arr) {
    arr.children && (arr = arr.children);
    if (arr.length == 0) { alert("没有书签"); return; }
    clear();
    arr.forEach((element, index) => {
      // console.log(``, element, index)
      // console.log(element.id)
      if (element.children) {
        // console.log(element)
        var div = document.createElement("div");
        div.setAttribute('class', 'folder')
        div.innerHTML = ` <img class="img" src="../images/folder.svg"/> 
            <div >${element.title}</div>
            <div class="zz" data-title="${element.title}" data-url="${element.url || ""}" data-id="${element.id}"></div>`
        document.getElementById("folderDir").appendChild(div)
      } else {
        let urlArr = element.url.split('/')
        let favicon = urlArr[0] + '//' + urlArr[2] + '/favicon.ico'
        var div = document.createElement("div");
        div.setAttribute('class', 'link')
        div.innerHTML = ` <img class="img" src="${favicon}" /> 
            <div >${element.title}</div>
            <div class="zz" data-title="${element.title}" data-url="${element.url || ""}" data-id="${element.id}"></div>`
        document.getElementById("linkDir").appendChild(div)
      }
    });
  }

  /* 点击文件夹事件 */
  function folderFn(event) {
    let { target } = event
    let id = target.getAttribute('data-id');
    let title = target.getAttribute('data-title');

    history.pushState({}, '', `#${id}`);
    document.title = title;
    addBookmarks(obj[id]);
    changeTip(title);
  }

  /* 打开链接 */
  function openLink(event) {
    let { target } = event
    let url = target.getAttribute('data-url')
    window.open(url)
  }

  /* 删除现有的选项 */
  function clear() {
    document.getElementById('folderDir').innerHTML = ''
    document.getElementById('linkDir').innerHTML = ''
  }

  // 设置标题碎屑
  let tipArr = []
  function changeTip(text) {
    if (text == '-') { tipArr.pop() }
    else if (text) { tipArr.push(text) }
    document.getElementById('tip').innerHTML = tipArr.join('/');
    db.setData('tipArr', tipArr)
  }

  // 切换刷新图片
  let refTime = 0, tt = 0;
  function refreshFn() {
    if (refTime) { clearInterval(refTime); refTime = 0; return; }
    let filePath = db.getData('filePath');
    getFileContent(filePath);
    refTime = setInterval(() => {
      document.getElementById('refresh').innerHTML = tt++ % 2 == 1 ? '🏃‍♂️' : '🚶‍♂️';
    }, 200);
  }

  // 退出到目录
  function outFn() {
    history.pushState({}, '', './folder.html');
    location.reload()
  }

  let bookmarks = db.getData('bookmarks') || [];
  let hash = location.hash.substring(1);
  let filePath = db.getData('filePath');
  if (bookmarks.length > 0) {
    if (db.getData('filePathOld') != filePath) {
      getFileContent(filePath);
      db.setData('filePathOld', filePath);
    } else {
      bookmarksToObj(bookmarks)
      addBookmarks(obj[hash]);
    }
  } else {
    getFileContent(filePath)
  }

  tipArr = db.getData('tipArr') || [];
  document.getElementById('fileName').innerHTML = db.getData('fileName');
  changeTip();

  window.addEventListener('popstate', function (e) {
    let hash = location.hash.substring(1);
    addBookmarks(obj[hash]);
    changeTip('-');
  });


</script>

</html>